import { createStore } from 'vuex'
import {login,getinfo} from '~/api/manager'
import {setToken ,removeToken} from '~/composables/auth'

// 创建一个新的 store 实例
const store = createStore({
    state () {
      return {
      //项目管理用户的相关信息
      user:{},
      //侧边宽度
      asideWidth:'250px',

      menus:[],
      ruleNames:[],
      }
    },
    mutations: {
      //记录用户的相关信息
      SET_USERINFO(state,user){
        //获取user:{}空对象
         state.user = user
      },
      // 展开缩起侧边
      handleAsideWidth(state){
        state.asideWidth = state.asideWidth == '250px' ? '64px':'250px'
      },
      SET_MENUS(state,menus){
        state.menus = menus
      },
      SET_RULENAMES(state,ruleNames){
        state.ruleNames = ruleNames;
      }
    },
    actions:{
      //登录
      login({commit},{username,password}){
        return new Promise((resolve,reject)=>{
         login(username,password).then(res=>{
          setToken(res.token)
          resolve(res)
         }).catch(err=>reject(err))
        })
    
      },
      //获取当前登录用户信息
      getinfo({ commit }){
       return new Promise((resolve,reject)=>{
        getinfo().then(res =>{
          commit("SET_USERINFO",res)
          commit('SET_MENUS',res.menus)
          //用户拥有的接口权限别名
          commit('SET_RULENAMES',res.ruleNames)
          //异步成功
          resolve(res)
          //异步不成功
        }).catch(err=>reject(err))
       })
      },
      //退出登录
      logout({commit}){
        removeToken()
        commit("SET_USERINFO",{})
      }
    }
  })
//   将store实例抛出
  export default store;